package edu.qd.learn.newchapter.chapter_thread.day01;

import java.io.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * io与多线程锁的案例
 *
 * @author 布衣
 */
public class IoDemo extends Thread {

    private final Lock lock = new ReentrantLock();

    private String fileName = "d:\\aa.txt";

    public IoDemo(String fileName) {
        this.fileName = fileName;
    }

    /**
     * d: a.txt 里面有一个数字 0
     */
    public void writeWordToTxt() {
        BufferedReader reader = null;
        BufferedWriter writer = null;

        try {
            File f = new File(fileName);
            reader = new BufferedReader(new FileReader(f));
            String s = reader.readLine();

            int num = Integer.parseInt(s);
            System.out.println(num);
            writer = new BufferedWriter(new FileWriter(f));
            writer.write(String.valueOf(++num));
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }


    @Override
    public void run() {
        try {
            lock.lock();
            writeWordToTxt();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        IoDemo ioDemo = new IoDemo("d:\\aa.txt");
        ioDemo.start();
        //第一个线程锁  第二个不能同时，
        Thread.sleep(100);
        IoDemo ioDemo1 = new IoDemo("d:\\aa.txt");
        ioDemo1.start();

        Thread.sleep(100);
        IoDemo ioDemo2 = new IoDemo("d:\\aa.txt");
        ioDemo2.start();
    }

}
